<?php
/**
 * 管理员日志搜索模型
 * Created by PhpStorm.
 * User: crstu
 * Date: 2016/4/27
 * Time: 9:33
 */

namespace common\models\DAO;

use yii\base\Model;
use yii\data\ActiveDataProvider;

class AdminLogSearch extends AdminLog
{

    public static function tableName()
    {
        return '{{%admin_log}}';
    }

    public function scenarios()
    {
        return Model::scenarios();
    }

    public function rules()
    {
        return [
            [['adminID'], 'safe'],
            [['type', 'action', 'controller', 'param', 'createTime'], 'string'],
        ];
    }

    public function search($params){

        $query = AdminLog::find();
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'sort' => [
                'defaultOrder' => [
                    'createTime' => SORT_DESC,
                ]
            ],
        ]);

        if(!($this->load($params) && $this->validate())){
            return $dataProvider;
        }

        //可以根据管理员ID，登录名，姓名查询
        if(!empty($this->adminID)){
            if(is_numeric($this->adminID)){
                $query->andFilterWhere(['adminID' => $this->adminID]);
            }else{
                $admin = Admin::find()->where(['like', 'adminName', $this->adminID])
                                      ->orWhere(['like', 'realName', $this->adminID])->asArray()->all();
                if(count($admin) > 0){
                    if(count($admin) === 1){
                        $query->andFilterWhere(['adminID' => $admin[0]['id']]);
                    }else{
                        $ids = [];
                        foreach ($admin as $v){
                            $ids = $v['id'];
                        }
                        $query->andFilterWhere(['in', 'adminID', $ids]);
                    }
                }else{
                    $query->andFilterWhere(['adminID' => $this->adminID]);
                }
            }
        }

        $query->andFilterWhere(['controller' => strtolower($this->controller)]);
        $query->andFilterWhere(['action' => strtolower($this->action)]);

        //时间范围筛选
        if(!empty($this->createTime)){
            $range = explode('~', $this->createTime);
            if(is_array($range) && count($range) == 2){
                $query->andFilterWhere(['>', 'createTime', strtotime($range[0])]);
                $query->andFilterWhere(['<', 'createTime', strtotime($range[1].' +1 days')]);
            }
        }

        return $dataProvider;

    }
    
}